<template>
  <div class="color-picker-warp">
    <div class="color-picker" @click.stop="openColorPicker">
      <div :style="colorStyle">
        <slot></slot>
      </div>
    </div>
    <div
      class="color-picker-c"
      :style="showPicker ? 'max-height:20000px;' : 'height:0;'"
    >
      <Sketch :show="showPicker" @changButton="changSketchButton"></Sketch>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineProps, defineEmits, ref, onUnmounted } from "vue";
import { Sketch } from "@ans1998/vue3-color";
import { onMounted } from "@vue/runtime-core";
const props = defineProps<{ value: string }>();
const showPicker = ref<boolean>(false);
const emits = defineEmits(["update:value"]);
const colorStyle = computed(() => {
  return {
    background: props.value,
  };
});

const changSketchButton = (item: { isOk: boolean; activeColor: string }) => {
  if (item.isOk) {
    emits("update:value", item.activeColor);
  }
  showPicker.value = false;
};

const openColorPicker = () => {
  showPicker.value = true;
};
const windowClickHandler = (e) => {
  if (
    [
      "vc-botton-container",
      "vc-input__input",
      "vc-input__label",
      "canvas-main overflow-auto",
      "vc-sketch",
      "vc-sketch-presets",
      "vc-botton-right",
      "vc-saturation",
      "vc-hue-container",
      "vc-alpha-picker",
      "anticon anticon-file-image",
      "vc-sketch-active-color",
      "vc-sketch-presets-color",
    ].indexOf(e.target.className) !== -1
  ) {
    return;
  }
  showPicker.value = false;
};
onMounted(() => {
  window.addEventListener("click", windowClickHandler);
});
onUnmounted(() => {
  window.removeEventListener("click", windowClickHandler);
});
</script>

<style lang="less" scoped>
.color-picker-warp {
  position: relative;
  width: 32px;
  height: 32px;
}
.color-picker {
  width: 100%;
  height: 100%;
  cursor: pointer;
  padding: 2px;
  border: 1px solid @primary-color;
  background-color: @white;
  & > div {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: @white;
  }
}
.color-picker-c {
  position: absolute;
  z-index: 999;
  top: 32px;
  right: 0;
  width: 200px;
  overflow: auto;
  transition: all 0.25s;
}
</style>
